/**
 * 工程师指标
 * @author hankangshuai
 * @since 2019-09-12
 */
layui.define(['form', 'select2', 'table', 'laydate', 'laytpl', 'formSelects', 'util'], function (exports) {
    const url = {
            dataSource: '/perf/master/loadData.action',
            export: '/perf/master/export.action',
            company: '/perf/getCompanyList.action',
            manageCompany: '/perf/getManageCompanyList.action',
            city: '/perf/getCityListByManageCompanyId.action',
            master: '/staff/master/list.action'
        }
    ;
    const exportFileName = "工程师指标导出" + new Date().toISOString() + '.xlsx';
    let $ = layui.$;
    let form = layui.form;
    let param = {};
    let util = layui.util;
    let table = layui.table;
    let laydate = layui.laydate;
    let formSelects = layui.formSelects;
    let yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
    let cols = [[
        {field: 'manageCompanyName', title: '服务公司', align: 'center', fixed: 'left'},
        {field: 'cityName', title: '城市', align: 'center', fixed: 'left'},
        {field: 'masterName', title: '工程师', align: 'center', fixed: 'left'},
        {field: 'newCount', title: '新单量', align: 'center'},
        {field: 'atvPrice', title: '客单价', align: 'center'},
        {field: 'reworkRate', title: '返修率', align: 'center', templet: d => d['reworkRate'] + '%'},
        {field: 'visitRate', title: '上门率', align: 'center', templet: d => d['visitRate'] + '%'},
        {field: 'scanedRate', title: '上门扫码率', align: 'center', templet: d => d['scanedRate'] + '%'},
        {field: 'subWeixincpRate', title: '企微添加率',  align: 'center', templet: d => d['subWeixincpRate'] + '%'},
        {field: 'appliqueRate', title: '贴花率', align: 'center', templet: d => d['appliqueRate'] + '%'},
        {field: 'completeRate', title: '完成率', align: 'center', templet: d => d['completeRate'] + '%'},
        {field: 'successRate', title: '成功率', align: 'center', templet: d => d['successRate'] + '%'},
        {field: 'visitSuccessRate', title: '上门成功率', align: 'center', templet: d => d['visitSuccessRate'] + '%'},
        {field: 'failRate', title: '失败率', align: 'center', templet: d => d['failRate'] + '%'},
        {field: 'visitFailRate', title: '上门失败率', align: 'center', templet: d => d['visitFailRate'] + '%'},
        // {field: 'commentRate', title: '用户评价率', align: 'center', templet: d => d['commentRate'] + '%'},
        {
            field: 'visitCommentRate',
            title: '评价上门准时率',
            width: 110,
            align: 'center',
            templet: d => d['visitCommentRate'] + '%'
        },
        {field: 'successStarAvg', title: '成功单平均评分', width: 110, align: 'center'},
        {field: 'partRate', title: '配件占比', align: 'center', templet: d => d['partRate'] + '%'},
        {field: 'finalPriceRate', title: '一口价占比', align: 'center', templet: d => d['finalPriceRate'] + '%'},
        {field: 'userPayAmountRate', title: '用户现金支付', align: 'center', templet: d => d['userPayAmountRate'] + '%'}
    ]];
    let tableIns;
    let initPage = () => {
        // 日期区间渲染
        let dateIns = laydate.render({
            elem: '#dateSpan'
            , trigger: 'click'
            , range: true
            , format: 'yyyy-MM-dd'
            , isInitValue: true
            , value: util.toDateString(yesterday, 'yyyy-MM-dd - yyyy-MM-dd')
        });
        tableIns = table.render({
            elem: '#zmn-table'
            , url: url.dataSource
            , cellMinWidth:100
            , height: "full-100"
            , cols
            , page: true
            , limit: 50
            , limits: [50, 100, 200]
            , where: {
                from: dateIns.config.value.split(' - ')[0],
                to: dateIns.config.value.split(' - ')[1]
            }
            , loading: true
            , toolbar: true
            , defaultToolbar: []
            , done: function (res) {
                //添加按钮
                ReportUtil.toobarRightAddButton([{
                    title: '帮助',
                    layEvent: 'CUSTOM_HELP',
                    icon: 'layui-icon-help'
                }, {
                    title: '导出',
                    layEvent: 'CUSTOM_EXPORT',
                    icon: 'layui-icon-export',
                    display: toolbarCompetence
                }]);
                ReportUtil.renderTotalRow(res.extData);
                // 修复reload的时候会携带上次查询参数
                param = this.where;
                document.tableIns = this;
            }
            , request: {
                pageName: 'pageIndex' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , response: {
                statusCode: 200
            }
        });
        // 初始化多选组件
        formSelects.config(null, {
            keyName: 'text'
        }, false);
        formSelects.btns([]);
        // 渲染下拉框
        //公司
        formSelects.data('company', 'server', {
            url: url.company
        });
        //服务公司
        formSelects.data('manageCompany', 'server', {
            url: url.manageCompany
        });
        //城市
        formSelects.data('city', 'server', {
            url: url.city
        });
        //城市
        formSelects.data('city', 'server', {
            url: url.city
        });

        /**
         * 格式化工程师列表列表项
         * @param {object} repo
         * @returns {string}
         */
        function formatRepoForMaster(repo) {
            if (repo.loading) {
                return '查询中...'
            }
            var name = repo.text + (repo.disabled ? '（离职）' : '');
            return '<div><div><i class="zmn-icon zmn-icon-worker"></i><span>' + name + '</span></div><div><i class="zmn-icon zmn-icon-phone"></i><span>' + repo.ext1.substr(0, 3) + '****' + repo.ext1.substr(7, 11) + '</span></div></div>';
        }

        /**
         * 使用 Select2 初始化工程师下拉框
         */
        function initMasterSelecteBySelect2() {
            $('#select-master').select2({
                theme: "layui",
                language: 'zh-CN',
                placeholder: '全部',
                allowClear: true,
                minimumInputLength: 1,
                dropdownAutoWidth: true,
                ajax: {
                    url: url.master,
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        let query = {
                            text: params.term,
                            companyId: formSelects.value('company', 'val')[0],
                            plat: platMark.ZMN
                        };
                        return query;
                    },
                    processResults: function (response) {
                        var results = [];
                        if (response.status === 200) {
                            results = response.data;
                        }
                        results = results.map((item) => {
                            item.id = item.value;
                            return item;
                        });

                        return {
                            results: results
                        };
                    }
                },
                escapeMarkup: function (markup) {
                    return markup;
                },
                templateResult: formatRepoForMaster,
            });
        }

        initMasterSelecteBySelect2();
    };
    let initEvent = () => {
        //表单验证
        form.verify({
            timeLimit: function (value, item) {
                const timeArr = value.toString().split(" - ", 2);
                const [from, to] = timeArr;
                const fromLong = new Date(from).getTime();
                const toLong = new Date(to).getTime();
                const total = (toLong-fromLong) / 1000;
                const day = parseInt(total / (24*60*60));
                if (day > 90) {
                    return '查询日期不能大于90天';
                }
            }
        });
        // 提交事件
        form.on('submit(query-submit)', function (formObj) {
            //时间区间兼容
            let dateSpan = formObj.field["dateSpan"].split(' - ');
            formObj.field["dateSpan"] = '';
            formObj.field["from"] = dateSpan[0];
            formObj.field["to"] = dateSpan[1];
            //修剪提交数据
            for (let fieldKey in formObj.field) {
                if (formObj.field[fieldKey] === "") {
                    delete formObj.field[fieldKey];
                }
            }
            document.tableIns.where = {};

            tableIns.reload({
                where: formObj.field,
                page: {curr: 1}
            });
            return false;
        });
        form.on('submit(zmn-form-reset)', function () {
            location.reload();
        });
        // 表格头工具事件
        table.on('toolbar(table-filter)', function (obj) {
            switch (obj.event) {
                // 表格导出
                case 'CUSTOM_EXPORT':
                    let that = this;
                    let ele = that.querySelector('i');
                    ReportUtil.toggleLoading(ele);
                    that.setAttribute('lay-event', '');
                    zmnUtil.download(url.export, param, exportFileName, (res) => {
                        that.setAttribute("lay-event", 'CUSTOM_EXPORT');
                        ReportUtil.toggleLoading(ele);
                    });
                    break;
                case "CUSTOM_HELP":
                    ReportUtil.tips(help_content.innerHTML, this);
                    break;
                default:
                    break;
            }
        });
        // 下拉框联动事件
        // 公司-服务公司
        formSelects.on('company', function () {
            let companyId = formSelects.value('company', 'val');
            formSelects.data('manageCompany', 'server', {
                url: url.manageCompany + '?' + $.param({companyId}, true)
            });
            return true;
        }, true);
        // 服务公司-城市
        formSelects.on('manageCompany', function () {
            let manageCompanyId = formSelects.value('manageCompany', 'val');
            formSelects.data('city', 'server', {
                url: url.city + '?' + $.param({manageCompanyId}, true)
            });
            return true;
        }, true);
    };

    initPage();
    initEvent();
    exports('oms_perf_master');
});
